import cron from 'node-cron';
import { AuditLogService } from './auditLogService';
import { logger } from '../utils/logger';
import { timeRanges } from '../utils/dateUtils';
import { AuditLogType } from '../models/auditLog';

interface TaskConfig {
  schedule: string;
  enabled: boolean;
}

interface RotationConfig {
  // 普通日志保留天数
  normalLogRetention: number;
  // 重要日志保留天数
  importantLogRetention: number;
  // 系统错误日志保留天数
  errorLogRetention: number;
  // 每次清理的批次大小
  batchSize: number;
}

const DEFAULT_CONFIG: RotationConfig = {
  normalLogRetention: 30,    // 普通日志保留30天
  importantLogRetention: 90, // 重要日志保留90天
  errorLogRetention: 180,    // 错误日志保留180天
  batchSize: 1000
};

// 重要日志类型
const IMPORTANT_LOG_TYPES = [
  AuditLogType.USER_CREATE,
  AuditLogType.USER_DELETE,
  AuditLogType.QUESTION_CREATE,
  AuditLogType.QUESTION_DELETE,
  AuditLogType.EVALUATION_SUBMIT
];

// 错误日志类型
const ERROR_LOG_TYPES = [
  AuditLogType.SYSTEM_ERROR,
  AuditLogType.ACCESS_DENIED
];

/**
 * 日志清理任务调度器
 */
export class LogRotationScheduler {
  private config: RotationConfig;
  private tasks: Map<string, cron.ScheduledTask>;
  
  constructor(config: Partial<RotationConfig> = {}) {
    this.config = { ...DEFAULT_CONFIG, ...config };
    this.tasks = new Map();
  }

  /**
   * 启动调度器
   */
  start() {
    // 每天凌晨2点运行日志清理
    this.schedule('0 2 * * *', this.rotateNormalLogs.bind(this));
    
    // 每周日凌晨3点运行重要日志清理
    this.schedule('0 3 * * 0', this.rotateImportantLogs.bind(this));
    
    // 每月1日凌晨4点运行错误日志清理
    this.schedule('0 4 1 * *', this.rotateErrorLogs.bind(this));
    
    logger.info('Log rotation scheduler started', {
      config: this.config
    });
  }

  /**
   * 停止调度器
   */
  stop() {
    this.tasks.forEach(task => task.stop());
    this.tasks.clear();
    logger.info('Log rotation scheduler stopped');
  }

  /**
   * 调度任务
   */
  private schedule(cronExpression: string, task: () => Promise<void>) {
    const scheduledTask = cron.schedule(cronExpression, async () => {
      try {
        await task();
      } catch (error) {
        logger.error('Log rotation task failed', { error });
      }
    });
    
    this.tasks.set(cronExpression, scheduledTask);
  }

  /**
   * 清理普通日志
   */
  private async rotateNormalLogs() {
    const normalLogTypes = Object.values(AuditLogType).filter(type => 
      !IMPORTANT_LOG_TYPES.includes(type) && 
      !ERROR_LOG_TYPES.includes(type)
    );

    await this.rotateLogs(
      this.config.normalLogRetention,
      normalLogTypes,
      'normal'
    );
  }

  /**
   * 清理重要日志
   */
  private async rotateImportantLogs() {
    await this.rotateLogs(
      this.config.importantLogRetention,
      IMPORTANT_LOG_TYPES,
      'important'
    );
  }

  /**
   * 清理错误日志
   */
  private async rotateErrorLogs() {
    await this.rotateLogs(
      this.config.errorLogRetention,
      ERROR_LOG_TYPES,
      'error'
    );
  }

  /**
   * 执行日志清理
   */
  private async rotateLogs(
    retentionDays: number,
    types: AuditLogType[],
    logType: string
  ) {
    const startTime = Date.now();
    logger.info(`Starting ${logType} log rotation`, {
      retentionDays,
      types
    });

    try {
      const result = await AuditLogService.cleanup(retentionDays, types);
      
      const duration = Date.now() - startTime;
      logger.info(`Completed ${logType} log rotation`, {
        deletedCount: result.deletedCount,
        duration,
        types
      });
      
    } catch (error) {
      logger.error(`Failed to rotate ${logType} logs`, {
        error,
        retentionDays,
        types
      });
      throw error;
    }
  }

  /**
   * 立即执行所有清理任务
   */
  async rotateAllLogs() {
    await Promise.all([
      this.rotateNormalLogs(),
      this.rotateImportantLogs(),
      this.rotateErrorLogs()
    ]);
  }
}
